import React, { PureComponent } from 'react';
import { Input, Form, InputNumber, Switch, Select, Icon } from 'antd';

export const EditableContext = React.createContext();

const { Option } = Select;

class EditableCell extends PureComponent {
  getInput = () => {
    const { type, title, render, cprops: compProps, options = [] } = this.props;
    let result = null;
    switch (type) {
      case 'input':
        result = <Input placeholder={title} />;
        break;
      case 'number':
        result = <InputNumber placeholder={title} />;
        break;
      case 'switch':
        result = (
          <Switch
            checkedChildren={<Icon type="check" />}
            unCheckedChildren={<Icon type="close" />}
          />
        );
        break;
      case 'select':
        result = (
          <Select placeholder={title} style={{ width: '100%' }}>
            {options.map(({ label, value }) => (
              <Option key={value} value={value}>
                {label}
              </Option>
            ))}
          </Select>
        );
        break;
      default:
        result = render;
    }
    return React.cloneElement(result, compProps);
  };

  renderCell = () => {
    const {
      editing,
      dataIndex,
      record,
      index,
      config,
      children,
      ...restProps
    } = this.props;
    const options =
      (typeof config === 'function' ? config(record) : config) || {};
    return (
      <td {...restProps}>
        {editing ? (
          <Form.Item
            style={{ margin: 0 }}
            name={options.key || dataIndex}
            rules={{
              initialValue: record[options.key] || record[dataIndex],
              ...options,
            }}
          >
            {this.getInput()}
          </Form.Item>
        ) : (
          children
        )}
      </td>
    );
  };

  render() {
    return (
      <EditableContext.Consumer>{this.renderCell}</EditableContext.Consumer>
    );
  }
}

export default EditableCell;
